package com.njcky.utils.test;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.StringReader;

/**
 * @Author: sj
 * @Date: 2022/2/9 10:19
 */
public class GxjhTestJob {

    private static final String ARITHMETIC = "AES/ECB/PKCS5Padding";

    private static String token = null;
    private static String aeskey = null;
    private static Long expirestime = 0L;



    //数据接口测试
    public static void main(String[] args) throws Exception {
        String appid = "b738b8307c63fa0bb889f43171525c16";
        String appsecret = "09b37640c6a27247b894f0a7405d5a37";
        String url_token = "http://10.115.48.157:8666/gxjh-api/api/token";
        String portid = "1796099789761183744";
        String url_data = "http://10.115.48.157:8666/gxjh-api/api/data";
        try {
            HttpClient httpClient = HttpClients.createDefault();
            if (token==null||aeskey==null||expirestime<System.currentTimeMillis()) {
                //获取token和数据密钥
                //定义一个Http连接器
                HttpPost httpPost = new HttpPost(url_token + "?appId=" + appid + "&appSecret=" + appsecret);
                //执行post请求
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
//                System.out.println("result1111: " + result);
                HashMap<String,Object> dataMap=XMLParserExample(result);
                token=dataMap.get("token").toString();
                aeskey=dataMap.get("aeskey").toString();
//                JSONObject resultJ = JSONObject.parseObject(result);
//                if (resultJ.getString("code").equals("200")) {//成功
//                    String data = resultJ.getString("data");
//                    JSONObject dataJ = JSONObject.parseObject(data);
//                    token = dataJ.getString("token");
//                    aeskey = dataJ.getString("aeskey");
//                    expirestime = dataJ.getLong("expirestime");
//                } else {
//                    System.out.println("获取token失败");
//                    return;
//                }
            }

            //获取数据
            //定义一个Http连接器
            HttpPost httpPost = new HttpPost(url_data);
            //设置请求头
            httpPost.setHeader("token",token);
            //设置请求参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("catalogId", "1796099789761183744"));
            params.add(new BasicNameValuePair("pageNo", "1"));
            params.add(new BasicNameValuePair("pageSize", "10"));
            params.add(new BasicNameValuePair("beginDate", "2024-01-01 00:00:00"));
            params.add(new BasicNameValuePair("endDate", "2024-05-01 00:00:00"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);// UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
            httpPost.setEntity(formEntity);
            //执行post请求
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
            HashMap<String,Object> dataMap=XMLParserExample2(result);
            //JSONObject resultJ = JSONObject.parseObject(result);
//            if (resultJ.getString("status").equals("200")) {//成功
//                String data = resultJ.getString("data");
                String AESKEY = createAESKey(aeskey);
                String decryptData = decrypt(dataMap.get("data").toString(),AESKEY);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static String createAESKey(String aeskey) {
        return (DigestUtils.md5DigestAsHex(aeskey.getBytes(StandardCharsets.UTF_8))).substring(0,16);
    }

    private static String decrypt(String encrypted,String key) {
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ARITHMETIC);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
            //采用base64算法进行转码,避免出现中文乱码
            byte[] encrypt = Base64.decodeBase64(encrypted);
            byte[] decryptBytes = cipher.doFinal(encrypt);
            return new String(decryptBytes,StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static HashMap<String,Object>  XMLParserExample(String xmlStr){
        HashMap<String,Object> resultMap=new HashMap<>();
//        String xmlString = "<books>" +
//                "<book>" +
//                "<title>Java Basics</title>" +
//                "<author>John Doe</author>" +
//                "</book>" +
//                "<book>" +
//                "<title>Advanced Java</title>" +
//                "<author>Jane Doe</author>" +
//                "</book>" +
//                "</books>";

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlStr)));

            document.getDocumentElement().normalize();
//            System.out.println("Root element :" + document.getDocumentElement().getNodeName());

            NodeList nodeList = document.getElementsByTagName("data");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;

//                    System.out.println("Book #" + (i+1));
//                    System.out.println("token : " + element.getElementsByTagName("token").item(0).getTextContent());
//                    System.out.println("aeskey : " + element.getElementsByTagName("aeskey").item(0).getTextContent());
                    resultMap.put("token", StringUtils.trimAllWhitespace(element.getElementsByTagName("token").item(0).getTextContent()));
                    resultMap.put("aeskey", StringUtils.trimAllWhitespace(element.getElementsByTagName("aeskey").item(0).getTextContent()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    private static HashMap<String,Object>  XMLParserExample2(String xmlStr){
        HashMap<String,Object> resultMap=new HashMap<>();
//        String xmlString = "<books>" +
//                "<book>" +
//                "<title>Java Basics</title>" +
//                "<author>John Doe</author>" +
//                "</book>" +
//                "<book>" +
//                "<title>Advanced Java</title>" +
//                "<author>Jane Doe</author>" +
//                "</book>" +
//                "</books>";

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlStr)));

            document.getDocumentElement().normalize();
//            System.out.println("Root element :" + document.getDocumentElement().getNodeName());

            NodeList nodeList = document.getElementsByTagName("data");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
//                    System.out.println(element.getTextContent());
                    resultMap.put("data", StringUtils.trimAllWhitespace(element.getTextContent()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }



    public static String getData(String catalogId,String pageSize,String pageNo,String beginDate,String endDate){
        String data="";
        String appid = "b738b8307c63fa0bb889f43171525c16";
        String appsecret = "09b37640c6a27247b894f0a7405d5a37";
        String url_token = "http://10.115.48.157:8666/gxjh-api/api/token";

        String portid = "1796099789761183744";
        String url_data = "http://10.115.48.157:8666/gxjh-api/api/data";
        try {

            HttpClient httpClient = HttpClients.createDefault();

            if (token==null||aeskey==null||expirestime<System.currentTimeMillis()) {
                //获取token和数据密钥
                //定义一个Http连接器
                HttpPost httpPost = new HttpPost(url_token + "?appId=" + appid + "&appSecret=" + appsecret);
                //执行post请求
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
//                System.out.println("result1111: " + result);
                HashMap<String,Object> dataMap=XMLParserExample(result);
                token=dataMap.get("token").toString();
                aeskey=dataMap.get("aeskey").toString();
//                JSONObject resultJ = JSONObject.parseObject(result);
//                if (resultJ.getString("code").equals("200")) {//成功
//                    String data = resultJ.getString("data");
//                    JSONObject dataJ = JSONObject.parseObject(data);
//                    token = dataJ.getString("token");
//                    aeskey = dataJ.getString("aeskey");
//                    expirestime = dataJ.getLong("expirestime");
//                } else {
//                    System.out.println("获取token失败");
//                    return;
//                }
            }

            //获取数据
            //定义一个Http连接器
            HttpPost httpPost = new HttpPost(url_data);
            //设置请求头
            httpPost.setHeader("token",token);
            //设置请求参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("catalogId", catalogId));
            params.add(new BasicNameValuePair("pageNo", pageNo));
            params.add(new BasicNameValuePair("pageSize", pageSize));
            params.add(new BasicNameValuePair("beginDate", beginDate));
            params.add(new BasicNameValuePair("endDate", endDate));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);// UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
            httpPost.setEntity(formEntity);
            //执行post请求
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "utf-8");
//            System.out.println("result222222: " + result);
            HashMap<String,Object> dataMap=XMLParserExample2(result);
            //JSONObject resultJ = JSONObject.parseObject(result);

//            if (resultJ.getString("status").equals("200")) {//成功
//                String data = resultJ.getString("data");
            String AESKEY = createAESKey(aeskey);
            String decryptData = decrypt(dataMap.get("data").toString(),AESKEY);
//            System.out.println("decryptData: " + decryptData);
//            }
            data=decryptData;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

}
